<?php

/**
 * Created by PhpStorm.
 * Author: ls
 * Time: 2023/9/19 16:21
 * Desc: 会员信息
 */
class Service_Api_Member_Info extends Contract_Api_Member_Info
{

    public function show(int $mid): array
    {
        $result              = Model_Member::get_member_byid($mid);
        $rank                = Model_Member::member_rank($mid, array('return' => 'all'));
        $result['rank_name'] = $rank['rankname'];
        $result['rank']      = $rank['current'];
        if (!empty($result['litpic'])) {
            $result['litpic'] = $this->get_member_header_pic($result['litpic']);
        }
        $result['idcard_pic'] = json_decode($result['idcard_pic'], true);
        if (!$result['idcard_pic']) {
            $result['idcard_pic'] = array();
        }
        foreach ($result['idcard_pic'] as &$v) {
            $v = $this->img_url($v);
        }
        if ($result) {
            $result['province'] = $result['province'] ?: '';
            $result['city']     = $result['city'] ?: '';
            $result['cardid']   = $result['cardid'] ?: '';
            $result['address']  = $result['address'] ?: '';
            $result['postcode'] = $result['postcode'] ?: '';
            $result['comefrom'] = $result['comefrom'] ?: '';

            unset($result['pwd']);
            unset($result['mid']);
            unset($result['safequestion']);
            unset($result['safeanswer']);
            unset($result['joinip']);
            unset($result['loginip']);
            unset($result['checkmail']);
            unset($result['checkphone']);
            unset($result['regtype']);
            unset($result['reg_from']);
            unset($result['reg_time']);
            unset($result['company_name']);
            unset($result['shop_id']);
            unset($result['last_shop_id']);
            unset($result['login_key']);
            unset($result['is_super']);
            unset($result['identity']);
            unset($result['last_logintime']);
            unset($result['mtype']);
            unset($result['jointime']);
            unset($result['logintime']);
            unset($result['is_virtual']);
            unset($result['connectid']);
        }
        return $result;
    }

    public function reset_password(int $mid, array $params): array
    {
        /**
         * @var $old_pwd
         * @var $pwd
         */
        extract($params);

        $member = Model_Member::get_member_byid($mid);
        if (empty($member)) {
            throw new Exception(__("error_user_noexists"));
        }

        if ($member['pwd'] != Model_Member::make_pwd($old_pwd)) {
            throw new Exception(__("原密码错误"));
        }

        DB::update('member')
            ->set(array('pwd' => Model_Member::make_pwd($pwd)))
            ->where('mid', '=', $mid)
            ->execute();

        return array();
    }

    public function modify(int $mid, array $params = array()): array
    {
        $field = array(
            'sex',
            'litpic',
            'nickname',
            'truename',
            'birth_date',
            'native_place',
            'cardid',
            'address',
            'qq',
            'wechat',
            'constellation',
            'signature'
        );
        $data  = array();
        foreach ($params as $k => $v) {
            if (in_array($k, $field)) {
                $data[$k] = $v;
            }
        }

        if (empty($data)) {
            throw new Exception(__('参数不能为空'));
        }

        DB::update('member')->set($data)->where('mid', '=', $mid)->execute();

        return array();
    }

    public function statistic(int $mid): array
    {
        $data   = Model_Api_V2_Member::calculate_num($mid);
        $status = array(
            'status_0' => 0,
            'status_1' => 0,
            'status_2' => 0,
            'status_5' => 0,
            'status_6' => 0
        );
        $exclude_typeids = [107,15];
        $orders = DB::select(DB::expr('status,count(status) as num'))
            ->from('member_order')
            ->where('memberid', '=', $mid)
            ->and_where('status', 'in', array(0, 1, 2, 5, 6))
            ->and_where(DB::expr(' and (typeid != 21 or (typeid = 21 and pid = 0))'))
            ->and_where('typeid', 'not in', $exclude_typeids)
            ->group_by('status')
            ->execute()->as_array();

        foreach ($orders as $v) {
            $status["status_{$v['status']}"] = $v['num'];
        }

        $pinlun = DB::select(DB::expr('count(ispinlun) as wait_comment'))
            ->from('member_order')
            ->where('memberid', '=', $mid)
            ->and_where('status', '=', 5)
            ->and_where(DB::expr(' and (typeid != 21 or (typeid = 21 and pid = 0))'))
            ->and_where('typeid', 'not in', $exclude_typeids)
            ->and_where('ispinlun', '=', 0)
            ->execute()
            ->current();

        $message = DB::select(DB::expr('count(id) as message'))
            ->from('message')
            ->where('memberid', '=', $mid)
            ->and_where('status', '=', 0)
            ->execute()
            ->current();
        return array_merge($data, $status, $pinlun, $message);
    }

    public function bind(int $mid, array $params = array()): array
    {
        /**
         * @var $msg_code
         * @var $msgtype
         * @var $user
         * @var $captcha_key
         * @var $code
         */
        extract($params);

        $msg_code_key = "{$msgtype}_send_code_{$user}";

        if (!Model_Api_V2_Common::verify_image_code($captcha_key, $code)) {
            throw new Exception(__("checkcode_error"));
        }

        if (Model_Api_V2_Common::cache('get', $msg_code_key) != $msg_code) {
            throw new Exception(__("account_sms_code_error"));
        }

        // 修改类型
        $user_type = strpos($user, '@') !== false ? 'email' : 'phone';
        // 修改的字段
        $field = $user_type == 'email' ? 'email' : 'mobile';
        // 判断是否被其它账号绑定
        $exists = DB::select('mid')
            ->from('member')
            ->where($field, '=', $user)
            ->and_where('mid', '!=', $mid)
            ->execute()
            ->current();
        if ($exists) {
            throw new Exception(__(($user_type == 'email' ? '邮箱' : '手机号') . "已被其他账号绑定"));
        }

        $member = Model_Member::get_member_byid($mid);
        // 检查是否已绑定该账号
        if ($user == $member[$field]) {
            throw new Exception(__(($user_type == 'email' ? '邮箱' : '手机号') . "已绑定"));
        }

        // 用户信息更新
        $update         = [];
        $update[$field] = $user;
        // 判断原有是否设置密码
        $old_email  = $member['email'];
        $old_mobile = $member['mobile'];
        $pwd        = $member['pwd'];
        if (empty($old_email) && empty($old_mobile) && empty($pwd)) {
            // 设置信息密码
            $new_pwd       = Model_Member::make_pwd($user);
            $update['pwd'] = $new_pwd;
        }
        DB::update('member')->set($update)->where('mid', '=', $mid)->execute();

        // 保存成功后赠送积分
        if ($user_type == 'email') {

            // 绑定邮箱送积分
            if (empty($old_email)) {
                $jifen = Model_Jifen::reward_jifen('sys_member_bind_email', $mid);
                if (!empty($jifen)) {
                    St_Product::add_jifen_log($mid, '绑定邮箱送积分' . $jifen, $jifen, 2);
                }
            }

            // 发送新密码
            if (!empty($data['pwd'])) {
                St_EmailService::send_member_email($user, NoticeCommon::MEMBER_THIRD_BIND_NEW_MSGTAG, $user, "");
            }
        } else {

            // 绑定手机送积分
            if (empty($old_mobile)) {
                $jifen = Model_Jifen::reward_jifen('sys_member_bind_phone', $mid);
                if (!empty($jifen)) {
                    St_Product::add_jifen_log($mid, '绑定手机送积分' . $jifen, $jifen, 2);
                }
            }

            // 发送新密码
            if (!empty($data['pwd'])) {
                St_SMSService::send_member_msg($user, NoticeCommon::MEMBER_THIRD_BIND_NEW_MSGTAG, $member['nickname'], $user, "");
            }
        }

        // 验证成功后清除图片缓存
        Model_Api_V2_Common::cache('set', $captcha_key, null);

        return array();
    }

    public function real_name(int $mid, array $params): array
    {
        /**
         * @var $truename
         * @var $cardid
         * @var $idcard_positive
         * @var $idcard_negative
         */
        extract($params);

        $path            = '/uploads/uniapp/idcard/' . date('Ymd') . '/';
        $idcard_positive = $this->save_base64_image($idcard_positive, $path);
        if (!$idcard_positive) {
            throw new Exception('证件保存失败');
        }

        $idcard_negative = $this->save_base64_image($idcard_negative, $path);
        if (!$idcard_negative) {
            throw new Exception('证件保存失败');
        }

        $member = ORM::factory('member')->where('mid', '=', $mid)->find();

        $member->verifystatus = 1;
        $member->truename     = $truename;
        $member->cardid       = $cardid;
        $member->idcard_pic   = json_encode(array(
            'front_pic' => $idcard_positive,
            'verso_pic' => $idcard_negative
        ));
        $member->save();

        if (!$member->saved()) {
            throw new Exception('提交失败');
        }

        return array();
    }

    public function is_bind_third(int $mid): int
    {
        if (!$mid) {
            return 0;
        }
        $member = Model_Member::get_member_info($mid);
        if ($member['reg_from'] == 3 && empty($member['mobile']) && Model_Sysconfig::get_configs(0, 'cfg_third_login_bind', true) == 2) {
            return 1;
        }
        return 0;
    }

    public function get_equity_detail(int $mid): array
    {
        $rank = Model_Member::member_rank($mid, array('return' => 'all'));
        if (empty($rank['current_rank']['id'])) {
            throw new Exception('暂无权益信息');
        }

        $grade_equity_list = DB::select()->from('member_grade_equity')->execute()->as_array();
        $grade_id_arr      = array_column($grade_equity_list, 'grade_id');
        $equity_id_arr     = array_column($grade_equity_list, 'equity_id');
        $style_id_arr      = array_column($grade_equity_list, 'style_id');
        $grade_equity_id   = array_combine($grade_id_arr, $equity_id_arr);
        $style_id          = array_combine($grade_id_arr, $style_id_arr);
        $grade_equity      = [];
        foreach ($grade_equity_list as $v) {
            $grade_equity[$v['grade_id']]['content'] = $v['content'];
            $grade_equity[$v['grade_id']]['info']    = $v;
        }
        $amount = 0;
        if (St_Functions::is_normal_app_install('system_wallet')) {
            $amount = DB::select()->from('wallet_member')->where('member_id', '=', $mid)->execute()->get('amount');
        }
        $list   = [];
        foreach ($rank['grade'] as $k => $v) {
            $num = $k + 1;
            if ($rank['grade'][$num]['grade_rules']) {
                if ($rank['grade'][$num]['grade_rules'] == 1) {
                    $percentage = bcdiv($rank['jifen'], $v['end'], 2) * 100;
                    $percentage = min($percentage, 100) . '%';
                    $diff       = bcsub($rank['grade'][$num]['begin'], $rank['jifen']);
                    $diff       = $diff > 0 ? $diff : 0;
                    $diff_info  = '升级LV' . ($num + 1) . '还需' . $diff . '积分';
                } else {
                    $percentage = bcdiv($amount, $rank['grade'][$num]['price'], 2) * 100;
                    $percentage = min($percentage, 100) . '%';
                    $diff_info  = '升级LV' . ($num + 1) . '需累计充值' . $rank['grade'][$num]['price'] . '元';
                }
            } else {
                if ($rank['grade'][$k]['grade_rules'] == 1) {
                    $percentage = bcdiv($rank['jifen'], $v['end'], 2) * 100;
                    $percentage = min($percentage, 100) . '%';
                } else {
                    $percentage = bcdiv($amount, $rank['grade'][$k]['price'], 2) * 100;
                    $percentage = min($percentage, 100) . '%';
                }
                $diff_info  = '最高等级';
            }
            if ($num < $rank['current']) {
                $percentage = '100%';
                $diff_info  = '';
            }
            $arr = [
                'grade_id'      => $v['id'],
                'grade_name'    => $v['name'],
                'grade_num'     => $num,
                'grade_rules'   => $v['grade_rules'],
                'grade_jifen'   => $v['begin'],
                'grade_price'   => $v['price'],
                'amount'        => $amount,
                'grade_style'   => $style_id[$v['id']] ? intval($style_id[$v['id']]) : 1,
                'grade_equity'  => [],
                'current_jifen' => $rank['jifen']>0 ? $rank['jifen'] : 0,
                'percentage'    => $percentage,
                'diff_info'     => $diff_info,
                'next_name'     => $rank['grade'][$num]['name'] ?: '',
                'equity_num'    => 0,
                'ty_equity'     => [],
                'set_equity'    => [],
                'content'       => [
                    'equity'  => self::handel_gift_info($grade_equity[$v['id']]['info']),
                    'explain' => $this->content_add_domain($grade_equity[$v['id']]['content']),
                ]
            ];

            $equity_id = $grade_equity_id[$v['id']];
            if ($equity_id) {
                $equity = Model_Equity::equity_list($equity_id);
                foreach ($equity['ty_list'] as &$ty) {
                    $ty['icon'] = Model_Api_V2_System::uniapp_img($ty['icon']);
                }
                foreach ($equity['set_list'] as &$set) {
                    $set['icon'] = Model_Api_V2_System::uniapp_img($set['icon']);
                }

                $arr['equity_num'] = count($equity['ty_list']) + count($equity['set_list']);
                $arr['ty_equity']  = $equity['ty_list'];
                $arr['set_equity'] = $equity['set_list'];
            }

            $list[] = $arr;
        }

        return $list;
    }

    public function handel_gift_info($grade_equity)
    {
        $gift_info = [];
        $equity_id = explode(',', $grade_equity['equity_id']);

        if (in_array(1, $equity_id) && $grade_equity['gift_jifen']) {
            $gift_info[] = '赠送' . $grade_equity['gift_jifen'] . '积分';
        }
        if (in_array(2, $equity_id)) {
            $gift_info[] = '享产品预订折扣';
        }
        if (in_array(3, $equity_id) && $grade_equity['birthday_coupon_id']) {
            $str                 = '生日有礼，赠送优惠券';
            $birthday_coupon_num = json_decode($grade_equity['birthday_coupon_num'], true);
            $birthday_coupon     = Model_Coupon::get_coupon_info($grade_equity['birthday_coupon_id']);

            foreach ($birthday_coupon as $b) {
                $str .= "【{$b['name']} × {$birthday_coupon_num[$b['id']]}】";
            }
            $gift_info[] = $str;
        }
        if (in_array(4, $equity_id) && $grade_equity['upgrade_coupon_id']) {
            $str                = '升级有礼，赠送优惠券';
            $upgrade_coupon_num = json_decode($grade_equity['upgrade_coupon_num'], true);
            $upgrade_coupon     = Model_Coupon::get_coupon_info($grade_equity['upgrade_coupon_id']);

            foreach ($upgrade_coupon as $u) {
                $str .= "【{$u['name']} × {$upgrade_coupon_num[$u['id']]}】";
            }
            $gift_info[] = $str;
        }
        if (in_array(5, $equity_id) && $grade_equity['new_user_coupon_id']) {
            $str                 = '新人有礼，赠送优惠券';
            $new_user_coupon_num = json_decode($grade_equity['new_user_coupon_num'], true);
            $new_user_coupon     = Model_Coupon::get_coupon_info($grade_equity['new_user_coupon_id']);

            foreach ($new_user_coupon as $new) {
                $str .= "【{$new['name']} × {$new_user_coupon_num[$new['id']]}】";
            }
            $gift_info[] = $str;
        }
        if (in_array(6, $equity_id) && $grade_equity['lottery_num']) {
            $gift_info[] = '赠送积分抽奖' . $grade_equity['lottery_num'] . '次';
        }

        return $gift_info;
    }

}